<?php
class Area 
{
	private $db;
	
	function __construct() {
		$this->db = godhouse::app()->db;
	}
	
	public function find($condition) {
		if($condition) 
			$condition = "WHERE $condition";
		return $this->db->fetch_first("SELECT * FROM god_area $condition");
	}
	
	public function findByPk($pk) {
		return $this->db->fetch_first("SELECT * FROM god_area WHERE id='$pk'");
	}
	
	public function findAll($condition='', $page=0, $ppp=GODHOUSE_PPP3, $order='') {
		if($condition) 
			$condition = "WHERE $condition";
		if($order) {
			$condition .= " ORDER BY $order";
		} else 
			$condition .= " ORDER BY id DESC";
		
		$sqladd = '';
		if($page && $ppp) {
			$start = ($page-1)*$ppp;
			$sqladd = "LIMIT $start, $ppp";
		}
		return $this->db->fetch_all("SELECT * FROM god_area $condition $sqladd");
	}
	
	public function findAllByPk($pk) {
		return $this->db->fetch_all("SELECT * FROM god_area WHERE id='$pk'");
	}
	
	public function update($condition, $att=array()){
		return $this->db->update('god_area', $att, $condition);
	}
	
	public function updateByPk($pk, $att=array()) {
		$condition = "id='$pk'";
		return $this->db->update('god_area', $att, $condition);
	}
	
	public function insert($att=array()){
		return $this->db->insert('god_area', $att);
	}
	
	public function delete($condition) {
		$this->db->query("DELETE FROM god_area WHERE $condition");
	}
	
	public function deleteByPk($pk) {
		$condition = "id='$pk'";
		$this->db->query("DELETE FROM god_area WHERE $condition");
	}
	
	public function count($condition) {
		if($condition) 
			$condition = "WHERE $condition";
		return $this->db->result_first("SELECT count(*) FROM god_area $condition");
	}
	
	/*----------------------------以下是新增方法----------------------------*/
	
	/**
	 * 根据ID返回两级信息字符串 格式如下：益阳->湖南
	 *
	 * @param unknown_type $areaId
	 * @return unknown
	 */
	public function getArea($areaId) {
		$str = '';
		$area = $this->findByPk($areaId);
		if($area) {
			$str = $area['name'];
			$pArea = $this->findByPk($area['fId']);
			if($pArea) {
				$pArea['name'] .= '->'. $str ;
			}
		}
		return $pArea['name'] ;
	}
	
	/**
	 * 根据ID返回两级信息数组 格式如下：array(areaId=>name, areaId=>name)
	 *
	 * @param unknown_type $areaId
	 * @return unknown
	 */
	public function getAreaArray($areaId) {
		$arr = array();
		$area = $this->findByPk($areaId);
		if($area) {
			$arr[$area['id']] = $area['name'];
			$pArea = $this->findByPk($area['fId']);
			if($pArea) {
				$arr[$pArea['id']] = $pArea['name'];
			}
		}
		return $arr;
	}
}
?>